<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      //封装一个检测数据类型的方法
      function checkType(data) {
        return Object.prototype.toString.call(data).slice(8, -1).toLowerCase();
      }

      function deepClone(obj) {
        let o = null;
        //判断当前进来拷贝的是基本类型还是对象类型(一般深拷贝只考虑数组和对象)
        if (checkType(obj) === "object") {
          //深拷贝一定会得到一个新的对象
          o = {};
        } else if (checkType(obj) === "array") {
          //深拷贝一定会得到一个新的数组
          o = [];
        } else {
          return obj;
        }

        for (let key in obj) {
          o[key] = deepClone(obj[key]);
        }

        //返回拷贝的对象
        return o;
      }
      //使用
      const obj1 = {
        name: "xiaowang",
        age: 18,
        score: {
          math: 100,
          ch: 80,
        },
      };

      const result = deepClone(obj1);
      console.log(result);
      console.log(result === obj1);
      console.log(result.score === obj1.score);
    </script>
  </body>
</html>
